package com.jeecms.wicool.manager.lottery.impl;



import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeecms.cms.entity.main.CmsUser;
import com.jeecms.common.hibernate3.Updater;
import com.jeecms.common.page.Pagination;
import com.jeecms.wicool.dao.lottery.ActiveConfigDao;
import com.jeecms.wicool.dao.lottery.LotteryConfigDao;
import com.jeecms.wicool.dao.lottery.SnDao;
import com.jeecms.wicool.entity.lottery.ActiveConfig;
import com.jeecms.wicool.entity.lottery.LotteryConfig;
import com.jeecms.wicool.entity.lottery.Sn;
import com.jeecms.wicool.manager.lottery.ActiveConfigMng;
import com.jeecms.wicool.manager.lottery.SnMng;
import com.jeecms.wicool.util.ConstantUtil;
import com.jeecms.wicool.util.SecurityUtil;

@Service
@Transactional
public class ActiveConfigMngImpl implements ActiveConfigMng {
	
	
	private ActiveConfigDao dao;
	@Autowired
	public void setDao(ActiveConfigDao dao) {
		this.dao = dao;
	}
	
	@Transactional(readOnly = true)
	public Pagination getPage(String name,Integer status,String startTime,String endTime, int pageNo, int pageSize,CmsUser user) {
		Pagination page = dao.getPage(name, status, startTime, endTime, pageNo, pageSize, user);
		return page;
	}
	@Override
	public ActiveConfig findById(Integer id) {
		ActiveConfig entity = dao.findById(id);
		return entity;
	}

	@Override
	public ActiveConfig update(ActiveConfig bean) {
		Updater<ActiveConfig> updater = new Updater<ActiveConfig>(bean);
		bean = dao.updateByUpdater(updater);
		return bean;
	}
	@Override
	public Set<LotteryConfig> updateLotterys(ActiveConfig bean,Collection<LotteryConfig> lotterys,String [] delLotteryId) {
		TreeSet<LotteryConfig> set= new TreeSet<LotteryConfig>(new Comparator(){
			@Override
			public int compare(Object arg0, Object arg1) {
				LotteryConfig a=(LotteryConfig) arg0;
				LotteryConfig b=(LotteryConfig) arg1;
				if(a.getId()<b.getId()){
					return -1;
				}else if(a.getId()>b.getId()){
					return 1;
				}
				return 0;
			}
		});
		 set.addAll(bean.getLotteryConfigs());  //原数据
		//先删除
	    if(delLotteryId!=null&&!delLotteryId[0].equals("")){
	    	for(String id:delLotteryId){      
	    		bean.getLotteryConfigs().remove(lotteryDao.findById(Integer.parseInt(id)));
	    		List<Sn> SnList=snDao.getSnByLottery(Integer.parseInt(id));        //先删除关联的Sn
	    		for(Sn s:SnList){
	    			snDao.deleteById(s.getId());   
	    		}
	    	lotteryDao.deleteById(Integer.parseInt(id));
	    	
	    	}
	    }
		
		// 再更新和增加
		Updater<LotteryConfig> updater;
		Set<LotteryConfig> toAdd = new HashSet<LotteryConfig>();
		for (LotteryConfig item : lotterys) {
			item.setActiveConfig(bean);
			if(item.getId()!=null){
				//更新
				List<Sn> snList=snDao.getSnByLottery(item.getId());
				if(item.getMaxCount()>snList.size()){
					//增加sn
					for(int i=0;i<item.getMaxCount()-snList.size();i++){
						Sn sn=new Sn();
						sn.setLotteryConfig(item);
						sn.setSn(createSn(item));
						sn.setStatus(0);
						sn.setShop(item.getActiveConfig().getShop());
						snDao.save(sn);
					}
				}if(item.getMaxCount()<snList.size()){
					for(int i=0;i<snList.size()-item.getMaxCount();i++){
						//相应减少sn
						snDao.deleteById(snList.get(i).getId());
						
					}
				}
				updater = new Updater<LotteryConfig>(item);
				lotteryDao.updateByUpdater(updater);
			}else{
				//增加
				toAdd.add(item);
			}
		}
		if(toAdd!=null&&toAdd.size()>0){
			for(LotteryConfig lc:toAdd){
				lc.setActiveConfig(bean);
				lotteryDao.save(lc);
				if(lc.getMaxCount()!=null){
				for(int i=0;i<lc.getMaxCount();i++){  //增加sn
					Sn sn=new Sn();
					sn.setLotteryConfig(lc);
					sn.setSn(createSn(lc));
					sn.setStatus(0);
					sn.setShop(lc.getActiveConfig().getShop());
					snDao.save(sn);
				}}
			}
		}
		set.addAll(toAdd);
		return set;
	}
	@Override
	public ActiveConfig save(ActiveConfig bean) {
		dao.save(bean);
		if(bean.getLotteryConfigs()!=null&&bean.getLotteryConfigs().size()>0){
			//将奖项生成sn码
			for(LotteryConfig lc : bean.getLotteryConfigs()){
				if(lc.getMaxCount()!=null&&lc.getMaxCount()>0){
					//可以生成sn码
					for(int i=0;i<lc.getMaxCount();i++){
						Sn sn=new Sn();
						sn.setLotteryConfig(lc);
						sn.setSn(createSn(lc));
						sn.setStatus(0);
						sn.setShop(lc.getActiveConfig().getShop());
						snDao.save(sn);
					}
				}
			}
		}
		return bean;
	}
	public String createSn(LotteryConfig bean){
		try {
			SimpleDateFormat simpleTime = new SimpleDateFormat("yyyyMMddHHmmss");
			String dateTime = simpleTime.format(new Date());
			int random=(int)(Math.random()*10000);
			String originalStr=bean.getActiveConfig().getShop().getShopJc()+dateTime+Integer.toString(random);
			String sn_mi=SecurityUtil.aesEncode(originalStr, ConstantUtil.key);
			return sn_mi;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
	}

	@Override
	public ActiveConfig deleteById(Integer id) {
		//先删除关联的sn
		ActiveConfig ac=dao.findById(id);
		Set<LotteryConfig> lcs=ac.getLotteryConfigs();
		for(LotteryConfig l:lcs){
			List<Sn> snList = snDao.getSnByLottery(l.getId());
			for(Sn s:snList){
				snDao.deleteById(s.getId());
			}
		}
		ActiveConfig bean = dao.deleteById(id);
		
		return bean;
	}
	@Override
	public ActiveConfig[] deleteByIds(Integer[] ids) {
		ActiveConfig[] beans = new ActiveConfig[ids.length];
		for (int i = 0,len = ids.length; i < len; i++) {
			beans[i] = deleteById(ids[i]);
		}
		return beans;
	}
	@Override
	public List<ActiveConfig> getAll(CmsUser user) {
		return dao.getAll(user);
	}
	@Autowired
	private LotteryConfigDao lotteryDao;
	@Autowired
	private SnDao snDao;
	
}